<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      label-position="right"
      label-width="100px"
      :model="pwd"
      :rules="formDataRules"
      ref="formRef"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwd.old_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwd.new_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pwd.re_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="doSubmit">修改密码</el-button>
        <el-button type="info" @click="resetBtn">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  //数据
  data() {
    return {
      pwd: {
        old_pwd: "",
        new_pwd: "",
        re_pwd: "",
      },
      //定义校验规则,
      formDataRules: {
        old_pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^\w{6,15}$/,
            message: "密码必须是6~15位的非空字符串",
            trigger: "blur",
          },
        ],
        new_pwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            pattern: /^\w{6,15}$/,
            message: "密码必须是6~15位的非空字符串",
            trigger: "blur",
          },
        ],
        re_pwd: [
          { required: true, message: "请输入确认新密码", trigger: "blur" },
          {
            pattern: /^\w{6,15}$/,
            message: "密码必须是6~15位的非空字符串",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              //value表示表单绑定的元素
              if (value === this.pwd.new_pwd) {
                callback();
              } else {
                callback(new Error("两次密码不一致"));
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  //方法
  methods: {
    //提交修改
    doSubmit() {
      //判断表单校验是否通过
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          //发送请求
          console.log(this.pwd)
          const { data: res } = await this.$axios.patch(
            "/my/updatepwd",
            this.pwd
          );
          this.$message.success(res.message);
        }
      });
    },
    //重置按钮
    resetBtn() {
      //恢复到表单组件初始的状态
      this.$refs.formRef.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
